import axios from 'axios'
import { getCookie } from '@/utils/cookie.js'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_API,
    // 超时
    timeout: 60000,
})

// request拦截器
service.interceptors.request.use(
    (config) => {
        // 是否需要设置 token
        let userinfo = getCookie('userinfo') || {}
        if (userinfo.token) {
            if (config.methods == 'post') {
                config.data = { ...(config.data || {}), token: userinfo.token }
            } else {
                config.params = {
                    ...(config.params || {}),
                    token: userinfo.token,
                }
            }
        }
        return config
    },
    (error) => {
        Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (res) => {
        // 未设置状态码则默认成功状态
        // const code = (res.data || {}).code || 200;
        // 获取错误信息
        // const msg = errorCode[code] || res.data.msg || errorCode['default']
        if ((res.data || {}).code == 401) {
            let href = location.href
            let redirect = href.split('#')[1] || ''
            location.href = href.split('#')[0] + '#/login?redirect=' + redirect
        }
        return res.data
    },
    (error) => {
        if (error == 'Request failed with status code 401' || error == 'Request failed with status code 403') {
            let href = location.href
            let redirect = href.split('#')[1] || ''
            location.href = href.split('#')[0] + '#/login?redirect=' + redirect
        }
        return Promise.reject(error)
    }
)

export default service
